#ifndef FACEVIDEOITEM_H
#define FACEVIDEOITEM_H

#include <QQuickItem>
#include <QQuickPaintedItem>
#include <QVideoFrame>
#include <QCamera>
#include <QTimer>
#include <QtQml/qqml.h>
#include <QDebug>
#include "cameravideobuffer.h"
#include "faceaction.h"
class FaceVideoItem : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(bool running READ running WRITE setRunning)
    Q_PROPERTY(QObject* videobuf READ videobuf WRITE setVideobuf)
    Q_PROPERTY(QObject* videoproc READ videoproc WRITE setVideoproc)
public:
    explicit FaceVideoItem(QQuickItem *parent = 0);

    void setRunning(bool r){
        if(mRunning==r||mpVideoBuffer==NULL)
            return;

        mRunning=r;
        if(r)
            connect(mpVideoBuffer,SIGNAL(newFrame(QVideoFrame)),this,SLOT(UpdateFrame(QVideoFrame)));
        else
            disconnect(mpVideoBuffer,SIGNAL(newFrame(QVideoFrame)),this,SLOT(UpdateFrame(QVideoFrame)));

    }
    bool running() const{
        return mRunning;
    }

    void setVideobuf(QObject* v)
    {
        mpVideoBuffer=qobject_cast<CameraVideoBuffer*>(v);
    }
    QObject* videobuf() const
    {
        return mpVideoBuffer;
    }
    QObject* videoproc() const
    {
        return mpFaceAction;
    }
    void setVideoproc(QObject* action)
    {
        qDebug()<<"setVideoproc";
        if(mpFaceAction==action)
            return;
        if(mpFaceAction)
        {
            disconnect(mpFaceAction,SIGNAL(FaceDetected(QVector<QRect>)),this,SLOT(UpdateFace(QVector<QRect>)));
        }

        if(false==connect(action,SIGNAL(FaceDetected(QVector<QRect>)),this,SLOT(UpdateFace(QVector<QRect>))))
            qDebug()<<"connect fail";
        else
            qDebug()<<"connect ok";
        mpFaceAction=qobject_cast<FaceAction*>(action);
    }

private:
    void StartCamera();
    void StopCamera();
protected:
    void paint(QPainter *painter);
    QSGNode * updatePaintNode(QSGNode * oldNode, UpdatePaintNodeData * updatePaintNodeData);

protected slots:
    void UpdateFrame(QVideoFrame);
    void UpdateFace(QVector<QRect> faces)
    {
        qDebug()<<"faces:"<<faces.size();
        mFaces=faces;
    }

private:
    CameraVideoBuffer *mpVideoBuffer;
    FaceAction        *mpFaceAction;
    bool              mRunning;
    QVector<QRect>    mFaces;
};

#endif // FACEVIDEOITEM_H
